package com.inter.aspect;

import com.inter.my.MyLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author yinxing
 * @date 2022-09-08
 */
@Aspect
@Component
@Slf4j
public class LogAspect {

    @Around("@annotation(myLog)")
    public Object around(ProceedingJoinPoint point, MyLog myLog) throws Throwable {
        //通过切入点获取目标class对象
        Class<?> aClass = point.getTarget().getClass();
        //获取接入点的类名
        String className = aClass.getName();
        //获取目标方法名称
        String methodName = point.getSignature().getName();
        //获取MyLog注解的value参数
        String value = myLog.value();
        //拿到方法的入参
        Object[] args = point.getArgs();
        StringBuffer stringBuffer = new StringBuffer();
        for (Object arg : args) {
            Map<String, Object> argMap = (Map<String, Object>) arg;
            stringBuffer.append(arg).append("\\");
        }
        UUID uuid = UUID.randomUUID();
        log.info("\n======YinXing Log-{}," +
                "类名[{}]," +
                "方法名[{}]" +
                "注解值:[{}]" +
                "参数:[{}]",uuid,className,methodName,value,stringBuffer);
        long startTime = System.currentTimeMillis();
        //运行目标方法
        Object[] objects =new Object[1];
        Map<String, Object> argMap = new HashMap<>();
        argMap.put("message","AOP消息");
        objects[0] = argMap;
        Object proceed = point.proceed(objects);
        long endTime = System.currentTimeMillis();
        log.info("\n======YinXing Log-{}," +
                "类名[{}]," +
                "方法名[{}]" +
                "注解值:[{}]" +
                "耗时:[{}ms]" +
                "返回参数:[{}]",uuid,className,methodName,value,endTime-startTime,proceed.toString());
        return proceed;
    }

}
